package com.lin.bank.config.exception;

import com.lin.bank.config.reponse.Result;
import com.lin.bank.config.reponse.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理程序
 *
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author Li
 * @Date 2022/3/1 16:13
 * @Version 1.0
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理特定异常类型,可以定义多个,这里只以ArithmeticException为例
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e){
        e.printStackTrace();
        log.error("算数异常"+e.getMessage());
        return Result.error().code(ResultCode.ARITHMETIC_EXCEPTION.getCode())
                .message(ResultCode.ARITHMETIC_EXCEPTION.getMessage());
    }

    /**
     * 空指针异常
     *
     * @param e e
     * @return {@link Result}
     */
    @ExceptionHandler(NullPointerException.class)
    public Result error(NullPointerException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error(ResultCode.NULL_POINTER_EXCEPTION);
    }

    /**
     * 数组越界异常
     *
     * @param e e
     * @return {@link Result}
     */
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public Result error(ArrayIndexOutOfBoundsException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error(ResultCode.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
    }

    /**
     * 错误
     * 处理业务异常,我们自己定义的异常
     *
     * @param e e
     * @return {@link Result}
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result error(BusinessException e){
        e.printStackTrace();
        log.error(e.getErrMsg());
        return Result.error().code(e.getCode())
                .message(e.getErrMsg());
    }

    /**
     * 全局处理异常，不管什么异常都可以捕获
     *
     * @param e e
     * @return {@link Result}
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error(ResultCode.UNKNOWN_EXCEPTION);
    }
}
